#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>

void ChildWrite(int wfd) {
    int cnt = 0;
    char buffer[1024];
    while(true) {
        snprintf(buffer,sizeof(buffer),"i am child: pid = %d, cnt = %d",getpid(),cnt++);
        write(wfd,buffer,strlen(buffer));
        sleep(2);
    }
}

void FatherRead(int rfd) {
    char buffer[1024];
    while(true) {
        size_t n = read(rfd,buffer,sizeof(buffer) - 1);
        if(n > 0) {
            buffer[n] = 0;
            printf("%s\n",buffer); 
            sleep(2);
        }
    }
}

int main()
{
    // 1.创建管道
    int fds[2] = {0}; // fd[0] r   fd[1] w
    int n = pipe(fds);
    if (n < 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "fds[0]:" << fds[0] << std::endl;
    std::cout << "fds[1]:" << fds[1] << std::endl;

    // 2.创建子进程

    pid_t id = fork();
    if (id == 0)
    {
        // child
        // code
        close(fds[0]);
        ChildWrite(fds[1]);
        exit(0);
    }
    // 3.关闭需要的读写段，形成通信信道
    close(fds[1]);
    FatherRead(fds[0]);
    waitpid(id, nullptr, 0);
    return 0;
}